<template>
  <div class="register-container">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="用户注册"
      left-arrow
      @click-left="onClickLeft"
    />

    <!-- 注册表单区域 -->
    <div class="register-content">
      <!-- Logo区域 -->
      <div class="logo-section">
        <div class="logo-icon">
          <van-icon name="user-circle-o" size="80" color="#1989fa" />
        </div>
        <h1 class="app-title">智慧医疗平台</h1>
        <p class="app-subtitle">创建您的账户，享受便民医疗服务</p>
      </div>

      <!-- 注册表单 -->
      <div class="register-form">
        <van-form @submit="onSubmit">
          <!-- 注册表单字段 -->
          <van-cell-group inset class="form-fields">
            <!-- 用户名输入 -->
            <van-field
              v-model="registerForm.userName"
              name="userName"
              label="用户名"
              placeholder="请输入用户名"
              left-icon="contact"
              :rules="userNameRules"
              clearable
              class="input-field"
            />
            
            <!-- 真实姓名输入 -->
            <van-field
              v-model="registerForm.realName"
              name="realName"
              label="真实姓名"
              placeholder="请输入真实姓名"
              left-icon="friends-o"
              :rules="realNameRules"
              clearable
              class="input-field"
            />
            
            <!-- 手机号输入 -->
            <van-field
              v-model="registerForm.phone"
              name="phone"
              label="手机号"
              placeholder="请输入手机号"
              left-icon="phone-o"
              :rules="phoneRules"
              clearable
              class="input-field"
            />
            
            <!-- 邮箱输入 -->
            <van-field
              v-model="registerForm.email"
              name="email"
              label="邮箱"
              placeholder="请输入邮箱地址"
              left-icon="envelop-o"
              :rules="emailRules"
              clearable
              class="input-field"
            />
            
            <!-- 密码输入 -->
            <van-field
              v-model="registerForm.password"
              type="password"
              name="password"
              label="密码"
              placeholder="请输入密码"
              left-icon="lock"
              :rules="passwordRules"
              clearable
              class="input-field"
            />
            
            <!-- 确认密码输入 -->
            <van-field
              v-model="registerForm.confirmPassword"
              type="password"
              name="confirmPassword"
              label="确认密码"
              placeholder="请再次输入密码"
              left-icon="lock"
              :rules="confirmPasswordRules"
              clearable
              class="input-field"
            />
          </van-cell-group>

          <!-- 用户协议 -->
          <div class="agreement-section">
            <van-checkbox v-model="agreeToTerms">
              我已阅读并同意
              <van-button type="primary" plain size="mini" @click="showTerms">
                《用户协议》
              </van-button>
              和
              <van-button type="primary" plain size="mini" @click="showPrivacy">
                《隐私政策》
              </van-button>
            </van-checkbox>
          </div>

          <!-- 注册按钮 -->
          <div class="register-button">
            <van-button
              round
              block
              type="primary"
              native-type="submit"
              :loading="loading"
              loading-text="注册中..."
              size="large"
              :disabled="!agreeToTerms"
            >
              立即注册
            </van-button>
          </div>
        </van-form>

        <!-- 登录链接 -->
        <div class="login-link">
          <span>已有账号？</span>
          <van-button type="primary" plain size="mini" @click="goToLogin">
            立即登录
          </van-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { Toast, Dialog } from 'vant'
import { apiService, type RegisterRequest } from '@/api/index'

/**
 * 用户注册页面组件
 * 提供用户注册功能，包含完整的表单验证和后端API调用
 */

const router = useRouter()
const loading = ref(false)
const agreeToTerms = ref(false)

/**
 * 注册表单数据
 */
const registerForm = reactive({
  userName: '',
  realName: '',
  phone: '',
  email: '',
  password: '',
  confirmPassword: ''
})

/**
 * 用户名验证规则
 */
const userNameRules = [
  { required: true, message: '请输入用户名' },
  { 
    validator: (value: string) => {
      const usernameRegex = /^[a-zA-Z0-9_]{4,20}$/
      return usernameRegex.test(value)
    }, 
    message: '用户名必须是4-20位字母、数字或下划线' 
  }
]

/**
 * 真实姓名验证规则
 */
const realNameRules = [
  { required: true, message: '请输入真实姓名' },
  { 
    validator: (value: string) => {
      const nameRegex = /^[\u4e00-\u9fa5a-zA-Z\s]{2,20}$/
      return nameRegex.test(value)
    }, 
    message: '真实姓名必须是2-20位中文或英文字符' 
  }
]

/**
 * 手机号验证规则
 */
const phoneRules = [
  { required: true, message: '请输入手机号' },
  { 
    validator: (value: string) => {
      const phoneRegex = /^1[3-9]\d{9}$/
      return phoneRegex.test(value)
    }, 
    message: '请输入正确的手机号格式' 
  }
]

/**
 * 邮箱验证规则
 */
const emailRules = [
  { required: true, message: '请输入邮箱地址' },
  { 
    validator: (value: string) => {
      const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
      return emailRegex.test(value)
    }, 
    message: '请输入正确的邮箱格式' 
  }
]

/**
 * 密码验证规则
 */
const passwordRules = [
  { required: true, message: '请输入密码' },
  { min: 6, message: '密码长度不能少于6位' },
  { 
    validator: (value: string) => {
      // 密码必须包含字母和数字
      const hasLetter = /[a-zA-Z]/.test(value)
      const hasNumber = /\d/.test(value)
      return hasLetter && hasNumber
    }, 
    message: '密码必须包含字母和数字' 
  }
]

/**
 * 确认密码验证规则
 */
const confirmPasswordRules = [
  { required: true, message: '请再次输入密码' },
  { 
    validator: (value: string) => {
      return value === registerForm.password
    }, 
    message: '两次输入的密码不一致' 
  }
]

/**
 * 返回上一页
 */
const onClickLeft = () => {
  router.back()
}

/**
   * 提交注册表单
   */
  const onSubmit = async (values: any) => {
    // 检查是否同意用户协议
    if (!agreeToTerms.value) {
      Toast.fail('请先同意用户协议和隐私政策')
      return
    }
    
    loading.value = true
    
    try {
      // 构造注册请求数据
      const registerData: RegisterRequest = {
        userName: values.userName,
        realName: values.realName,
        phone: values.phone,
        email: values.email,
        password: values.password,
        confirmPassword: values.confirmPassword
      }
      
      console.log('发送注册请求:', registerData)
      
      // 调用后端注册API
      const response = await apiService.register(registerData)
      
      console.log('注册响应:', response)
      
      // 检查注册结果
      if (response.code === 200) {
        // 注册成功
        Toast.success(response.message || '注册成功！')
        
        // 显示成功对话框并跳转到登录页面
        Dialog.alert({
          title: '注册成功',
          message: '恭喜您注册成功！请使用您的账号密码登录。',
          confirmButtonText: '去登录'
        }).then(() => {
          router.replace('/login')
        })
      } else {
        // 注册失败
        Toast.fail(response.message || '注册失败')
      }
    } catch (error) {
      console.error('注册请求失败:', error)
      
      // 更详细的错误提示
      if (error instanceof TypeError && error.message.includes('fetch')) {
        Toast.fail('网络连接失败，请检查：\n1. 后端服务是否启动\n2. 端口5049是否开放\n3. 代理配置是否正确')
      } else {
        Toast.fail('注册失败：' + (error as Error).message)
      }
    } finally {
      loading.value = false
    }
  }

/**
 * 显示用户协议
 */
const showTerms = () => {
  Dialog.alert({
    title: '用户协议',
    message: '这里是用户协议的内容...\n\n1. 用户应当遵守相关法律法规\n2. 保护个人账户安全\n3. 不得恶意使用平台服务\n4. 平台有权对违规行为进行处理',
    confirmButtonText: '我知道了'
  })
}

/**
 * 显示隐私政策
 */
const showPrivacy = () => {
  Dialog.alert({
    title: '隐私政策',
    message: '这里是隐私政策的内容...\n\n1. 我们重视您的隐私保护\n2. 收集的信息仅用于提供服务\n3. 不会向第三方泄露您的个人信息\n4. 您有权查看和修改个人信息',
    confirmButtonText: '我知道了'
  })
}

/**
 * 跳转到登录页面
 */
const goToLogin = () => {
  router.push('/login')
}
</script>

<style scoped>
.register-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  flex-direction: column;
  overflow-y: auto;
}

.register-content {
  flex: 1;
  padding: 16px;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  padding-top: 20px;
  min-height: calc(100vh - 46px); /* 减去导航栏高度 */
}

/* Logo区域样式 */
.logo-section {
  text-align: center;
  margin-bottom: 24px;
  padding-top: 10px;
}

.logo-icon {
  margin-bottom: 12px;
}

.app-title {
  font-size: 24px;
  font-weight: bold;
  color: white;
  margin-bottom: 6px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.app-subtitle {
  font-size: 13px;
  color: rgba(255, 255, 255, 0.8);
  line-height: 1.4;
  margin-bottom: 0;
}

/* 注册表单样式 */
.register-form {
  background: white;
  border-radius: 16px;
  padding: 20px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  margin-bottom: 16px;
}

/* 表单字段样式 */
.form-fields {
  margin-bottom: 16px;
}

.input-field {
  margin-bottom: 12px;
}

/* 调整输入框高度和内边距 */
.input-field :deep(.van-field) {
  padding: 16px 12px;
  min-height: 56px;
}

.input-field :deep(.van-field__label) {
  font-size: 14px;
  line-height: 1.4;
  min-width: 80px;
  flex-shrink: 0;
}

.input-field :deep(.van-field__body) {
  flex: 1;
  min-width: 0;
}

/* 深度选择器修复输入框样式 */
.input-field :deep(.van-field__control input) {
  line-height: 1.5;
  vertical-align: baseline;
  font-family: inherit;
  font-size: 16px;
  height: 24px;
  padding: 8px 0;
  text-indent: 0 !important;
  padding-left: 0 !important;
  margin-left: 0 !important;
  transform: none !important;
  position: relative;
  left: 0 !important;
  width: 100% !important;
  box-sizing: border-box;
}

/* 修复placeholder样式，确保提示词完整显示 */
.input-field :deep(.van-field__control input::placeholder) {
  color: #c8c9cc;
  font-size: 14px;
  line-height: 1.5;
  white-space: nowrap;
  overflow: visible;
  text-overflow: ellipsis;
  opacity: 1;
}

/* 确保输入控件有足够空间 */
.input-field :deep(.van-field__control) {
  flex: 1;
  min-width: 0;
  padding-left: 8px;
}

/* 修复密码输入框样式 */
.input-field :deep(.van-field__control input[type="password"]) {
  line-height: 1.5;
  vertical-align: baseline;
  font-family: inherit;
  font-size: 16px;
  height: 24px;
  padding: 8px 0;
  text-indent: 0 !important;
  padding-left: 0 !important;
  margin-left: 0 !important;
  transform: none !important;
  position: relative;
  left: 0 !important;
}

/* 修复浏览器自动填充样式 */
.input-field :deep(.van-field__control input:-webkit-autofill) {
  -webkit-text-fill-color: #323233 !important;
  transition: background-color 5000s ease-in-out 0s;
  text-indent: 0 !important;
  padding-left: 0 !important;
}

/* 确保所有输入框样式一致 */
.input-field :deep(.van-field__control) {
  text-align: left;
}

.agreement-section {
  margin: 16px 0;
  padding: 0 4px;
}

.agreement-section :deep(.van-checkbox__label) {
  font-size: 12px;
  color: #646566;
  line-height: 1.4;
}

.register-button {
  margin: 20px 0 16px 0;
}

/* 登录链接样式 */
.login-link {
  text-align: center;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #ebedf0;
  font-size: 14px;
  color: #646566;
}

.login-link span {
  margin-right: 8px;
}

/* 响应式设计 */
@media (max-width: 375px) {
  .register-content {
    padding: 12px;
    padding-top: 16px;
  }
  
  .register-form {
    padding: 16px;
  }
  
  .logo-section {
    margin-bottom: 20px;
    padding-top: 8px;
  }
  
  .app-title {
    font-size: 22px;
  }
  
  .app-subtitle {
    font-size: 12px;
  }
}

/* 深色模式适配 */
@media (prefers-color-scheme: dark) {
  .register-form {
    background: #1e1e1e;
    color: white;
  }
  
  .login-link {
    border-top-color: #333;
    color: #999;
  }
}
</style>